// @ts-ignore
import MarkdownIt from 'markdown-it'
// @ts-ignore
import MarkdownItContainer from 'markdown-it-container'
// @ts-ignore
// import MarkdownItAttrs from 'markdown-it-attrs'

import MarkdownItEmoji from 'markdown-it-emoji'

import fullEmoji from 'markdown-it-emoji/lib/data/full.json'
import {buildAssetsPath} from "../../../../env/env";

const Prism = (window as any).Prism

const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    xhtmlOut: true,
    // breaks: true,
    langPrefix: true,

    highlight: function (str: string, lang: string) {
        if (lang && Prism.languages[lang] && lang !== 'none') {
            try {
                return `<div class="pl-prism"><pre class="line-numbers"><code class="language-${lang}">${md.utils.escapeHtml(str)}</code></pre></div>`
            } catch (e) {
                console.error(e)
                return 'Render Prism Error!'
            }
        }

        return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
    }

})

/**
 * 自定义代码块
 * @author  韦胜健
 * @date    2020/9/13 8:09
 */
const blocks = [
    {tag: 'tip', title: '提示'},
    {tag: 'success', title: '提示'},
    {tag: 'warn', title: '注意'},
    {tag: 'error', title: '注意'},
];

blocks.forEach(block => {
    md.use(MarkdownItContainer, block.tag, {
        render(tokens: any[], idx: number) {
            const token = tokens[idx]
            if (token.nesting === 1) {
                // opening tag
                let [blockName, title] = token.info.trim().split(' ')
                title = title || block.title
                return `<div class="${block.tag} custom-block"> <p class="block-title">${title}</p>`;
            } else {
                // closing tag
                return '</div>\n';
            }
        },
    })
})

md.use((window as any).markdownItAttrs, {});
md.use(MarkdownItEmoji)

md.renderer.rules.emoji = function (token: string, idx: number) {
    // @ts-ignore
    return `<span class="emoji emoji_${token[idx].markup}">${fullEmoji[token[idx].markup]}</span>`;
};

export function renderMarkdown(markdownString: string | undefined, el: HTMLElement): void {
    let innerHtml = !!markdownString ? md.render(markdownString) : null
    if (!!innerHtml) {
        innerHtml = (innerHtml.replace(/<a(.*?)>(.*?)<\/a>/g, `<a$1><span>$2</span><i class="pl-icon-font pli-link"></i></a>`) as string)
            .replace(/<img src="(.*?)".*>/g, (...match) => {
                let [, src] = match
                src = /https?:\/\//.test(src) ? src : buildAssetsPath(src)
                return `<div class="pl-markdown-img"><img src="${src}"></div>`
            })
        el.innerHTML = innerHtml
        Prism.highlightAllUnder(el)
    } else {
        el.innerHTML = innerHtml
    }
}